<script setup lang="ts">
  import SingleAddress from '@/components/business/address/single-address/SingleAddress.vue'
  import infoTip from '@/config/info-tip'
  import {
    useReturnFactoryLogisticsInfoSave,
    useGetReceiptAddress,
  } from '@/services/pages/return-factory/useReturnFactory'
  import { FormInstance, TableInstance, UploadFile, UploadRawFile } from 'element-plus'
  import { computed, PropType, ref, watch } from 'vue'
  import { verifyPhone } from '@/utils/validate'
  import { HMessage, HMessageBox } from '@/components/common/message'
  import HFilePreview from '@/components/common/file-preview/index.vue'
  import { fileUpload } from '@/api/upload'

  const {
    address: receiptAddress,
    getAddressLoading: getReceiptAddressLoading,
    getAddress: getReceiptAddress,
  } = useGetReceiptAddress()
  const { loading: saveLoading, form, save } = useReturnFactoryLogisticsInfoSave()

  defineOptions({
    name: 'LogisticsFillInModalReturnFactoryDetail',
  })

  const props = defineProps({
    selectedLogisticsList: {
      type: Array as PropType<Array<ReturnFactoryDetailGood>>,
      default: () => [],
    },
    checkMethod: {
      type: Number as PropType<1 | 2>,
      default: () => 1,
    },
    returnFactoryId: {
      type: String,
      required: true,
    },
  })

  const emits = defineEmits<{
    (e: 'update'): void
  }>()

  const visible = defineModel('visible', { type: Boolean, default: false })
  const formInstance = ref<null | FormInstance>(null)
  const tableInstance = ref<null | TableInstance>(null)
  const logisticsList = ref<
    Array<
      ReturnFactoryDetailGood & { file: { file: UploadRawFile | null; url: string; name: string } }
    >
  >([])
  const rules = {
    receiveUsername: [{ required: true, message: '请输入收货人姓名', trigger: ['change', 'blur'] }],
    receiveProvince: [
      { required: true, message: '请选择收货地址', trigger: ['change', 'blur'] },
      {
        validator: (rule: any, value: any, callback: any) => {
          if (!form.value.receiveProvince || !form.value.receiveCity || !form.value.receiveArea) {
            callback(new Error('请选择收货地址'))
            return
          }
          callback()
        },
        trigger: ['change', 'blur'],
      },
    ],
    receivePhone: [
      { required: true, message: '请输入收货人手机号', trigger: ['change', 'blur'] },
      {
        validator: (rule: any, value: any, callback: any) => {
          if (!verifyPhone(form.value.receivePhone)) {
            callback(new Error('格式不正确'))
            return
          }

          callback()
        },
        trigger: ['change', 'blur'],
      },
    ],
    receiveAddress: [{ required: true, message: '请输入详细地址', trigger: ['change', 'blur'] }],
  }
  const allLogisticsEnterprise = ref('')
  const allLogisticsEnterprisePopoverVisible = ref(false)
  const allLogisticsNo = ref('')
  const allLogisticsNoPopoverVisible = ref(false)

  /**
   * tableIndex - 没有填写物流信息的表格行
   * noEnterprise - 物流公司是否为空
   * noOrderNum - 物流单号是否为空
   */
  const noLogisticsInfoTipSet = ref({
    tableIndex: -1,
    noEnterprise: false,
    noOrderNum: false,
  })

  const address = computed(() => {
    return {
      province: form.value.receiveProvince,
      city: form.value.receiveCity,
      area: form.value.receiveArea,
      town: '',
    }
  })

  const onConfirmMultipleFillInLogisticsEnterprise = () => {
    form.value.repairGoodsLogisticsVos = form.value.repairGoodsLogisticsVos.map((item) => {
      return {
        id: item.id,
        sendBackLogisticsName: allLogisticsEnterprise.value,
        sendBackLogisticsNo: item.sendBackLogisticsNo,
        sendBackLogisticsFile: item.sendBackLogisticsFile,
      }
    })
    allLogisticsEnterprisePopoverVisible.value = false
    allLogisticsEnterprise.value = ''
  }

  const onConfirmMultipleFillInLogisticsNo = () => {
    form.value.repairGoodsLogisticsVos = form.value.repairGoodsLogisticsVos.map((item) => {
      return {
        id: item.id,
        sendBackLogisticsName: item.sendBackLogisticsName,
        sendBackLogisticsNo: allLogisticsNo.value,
        sendBackLogisticsFile: item.sendBackLogisticsFile,
      }
    })
    allLogisticsNoPopoverVisible.value = false
    allLogisticsNo.value = ''
  }

  const handleChangeAddress = (val: {
    province: string
    city: string
    area: string
    town: string
  }) => {
    form.value.receiveProvince = val.province
    form.value.receiveCity = val.city
    form.value.receiveArea = val.area
  }

  const onConfirm = async () => {
    if (!formInstance.value || !tableInstance.value) return
    if (logisticsList.value.some((item) => !item.file.file)) {
      HMessage.error('返厂附件不能为空')
      return
    }

    try {
      await formInstance.value.validate()
      noLogisticsInfoTipSet.value = {
        tableIndex: -1,
        noEnterprise: false,
        noOrderNum: false,
      }

      for (let i = 0; i < logisticsList.value.length; i++) {
        const file = logisticsList.value[i].file.file
        if (file) {
          const res = await fileUpload([file])
          if (res.data.code === 20000) {
            logisticsList.value[i].file.url = res.data.data.rows[0]
            form.value.repairGoodsLogisticsVos[i].sendBackLogisticsFile = res.data.data.rows[0]
          }
        }
      }

      const noLogisticsInfoIndex = form.value.repairGoodsLogisticsVos.findIndex(
        (item) => !item.sendBackLogisticsName || !item.sendBackLogisticsNo,
      )
      if (noLogisticsInfoIndex !== -1) {
        tableInstance.value.setScrollTop(noLogisticsInfoIndex * 45)
        const logisticsInfo = form.value.repairGoodsLogisticsVos[noLogisticsInfoIndex]
        noLogisticsInfoTipSet.value = {
          tableIndex: noLogisticsInfoIndex,
          noEnterprise: !logisticsInfo.sendBackLogisticsName,
          noOrderNum: !logisticsInfo.sendBackLogisticsName,
        }
        return
      }

      const res = await save(props.returnFactoryId)
      if (res.code === 20000) {
        HMessage.success(infoTip.returnFactory.detail.save_logistics_success)
        hideDrawer()
        emits('update')
        return
      }

      HMessageBox.error(res.message)
    } catch (error) {
      // error
    }
  }

  const hideDrawer = () => {
    form.value = {
      receiveAddress: '',
      receiveArea: '',
      receiveCity: '',
      receivePhone: '',
      receiveProvince: '',
      receiveUsername: '',
      repairGoodsLogisticsVos: [],
    }
    visible.value = false
  }

  const handleFillLogisticsNoInput = (index: number, val: string) => {
    form.value.repairGoodsLogisticsVos[index].sendBackLogisticsNo = val.replace(/[^\da-zA-Z]/g, '')
    if (val) {
      noLogisticsInfoTipSet.value.noOrderNum = false
      return
    }
    noLogisticsInfoTipSet.value.tableIndex = index
    noLogisticsInfoTipSet.value.noOrderNum = true
  }

  const handleMultipleFillLogisticsNoInput = (val: string) => {
    allLogisticsNo.value = val.replace(/[^\da-zA-Z]/g, '')
  }

  const handleUploadFile = (file: UploadFile, index: number) => {
    if (file.raw) {
      logisticsList.value[index].file = {
        file: file.raw,
        url: URL.createObjectURL(file.raw),
        name: file.name,
      }
    }
  }

  const handleDeleteFile = (rowIndex: number) => {
    logisticsList.value[rowIndex].file = {
      file: null,
      url: '',
      name: '',
    }
  }

  watch(
    visible,
    async (value) => {
      if (value) {
        await getReceiptAddress(props.returnFactoryId)
        form.value.receiveAddress = receiptAddress.value.factoryReceiveAddress
        form.value.receiveArea = receiptAddress.value.factoryReceiveArea
        form.value.receiveCity = receiptAddress.value.factoryReceiveCity
        form.value.receiveProvince = receiptAddress.value.factoryReceiveProvince
        form.value.receiveUsername = receiptAddress.value.factoryReceiveUsername
        form.value.receivePhone = receiptAddress.value.factoryReceivePhone
      }

      // if (value && props.checkMethod === 1) {
      //   await getWaitCheckGoodList(props.returnFactoryId)
      //   logisticsList.value = waitGoodList.value
      // }

      // if (props.checkMethod === 2) {
      logisticsList.value = props.selectedLogisticsList.map((item) => {
        return {
          ...item,
          file: {
            file: null,
            url: '',
            name: '',
          },
        }
      })
      // }

      form.value.repairGoodsLogisticsVos = logisticsList.value.map((item) => {
        return {
          id: item.id,
          sendBackLogisticsName: '',
          sendBackLogisticsNo: '',
          sendBackLogisticsFile: '',
        }
      })
    },
    { immediate: true },
  )
</script>

<template>
  <h-drawer
    v-model="visible"
    title="填写返厂物流"
    :width="1000"
    unit="px"
    :loading="saveLoading || getReceiptAddressLoading"
    @close="hideDrawer"
  >
    <div class="drawer-body">
      <div class="basic-info">
        <div class="title">基本信息</div>
        <el-form
          ref="formInstance"
          label-position="top"
          :model="form"
          :rules="rules"
          inline-message
          class="modal_form_content"
        >
          <!-- 收货人姓名 -->
          <el-form-item label="收货人姓名" prop="receiveUsername">
            <el-input
              v-model.trim="form.receiveUsername"
              placeholder="收货人姓名"
              maxlength="50"
              disabled
            />
          </el-form-item>

          <!-- 收货地址 -->
          <el-form-item label="收货地址" prop="receiveProvince">
            <single-address :disabled="true" :address="address" @change="handleChangeAddress" />
          </el-form-item>

          <!-- 收货人手机号 -->
          <el-form-item label="收货人手机号" prop="receivePhone">
            <el-input
              v-model.trim="form.receivePhone"
              placeholder="收货人手机号"
              maxlength="11"
              disabled
            />
          </el-form-item>

          <!-- 详细地址 -->
          <el-form-item label="详细地址" prop="receiveAddress">
            <el-input
              v-model.trim="form.receiveAddress"
              type="textarea"
              resize="both"
              maxlength="200"
              show-word-limit
              disabled
              placeholder="请输入详细地址"
            />
          </el-form-item>
        </el-form>
      </div>
      <div class="logistics-list">
        <div class="title">物流列表</div>
        <div class="table">
          <el-table
            ref="tableInstance"
            :border="true"
            stripe
            :data="logisticsList"
            :max-height="350"
          >
            <!-- 序号 -->
            <el-table-column label="序号" type="index" :align="'center'" fixed="left" width="50" />

            <!-- 条码 -->
            <el-table-column width="120" label="条码" prop="code" show-overflow-tooltip />

            <!-- 产品信息 -->
            <el-table-column
              min-width="300"
              label="产品信息"
              prop="goodsModel"
              show-overflow-tooltip
            >
              <template #default="{ row }">
                {{ `${row.goodsName}、${row.goodsModel}、${row.goodsSpec}、${row.goodsCode}` }}
              </template>
            </el-table-column>

            <!-- 返厂附件 -->
            <el-table-column label="返厂附件" width="140">
              <template #default="{ $index, row }">
                <el-upload
                  v-if="!row.file.file"
                  action="#"
                  multiple
                  accept="*"
                  :auto-upload="false"
                  :show-file-list="false"
                  :on-change="(file: UploadFile) => handleUploadFile(file, $index)"
                  drag
                  class="file"
                >
                  <el-icon :size="24" color="#007cff">
                    <UploadFilled />
                  </el-icon>
                </el-upload>
                <div v-if="row.file.file" style="display: flex; column-gap: 6px">
                  <div style="flex: 1; width: 0">
                    <h-file-preview :file-url="row.file.url" :file-name="row.file.name" />
                  </div>
                  <h-link type="error" @click="handleDeleteFile($index)">删除</h-link>
                </div>
              </template>
            </el-table-column>

            <!-- 寄回物流公司名称 -->
            <el-table-column label="寄回物流公司名称" width="200">
              <template #header>
                <div class="table-cell-header">
                  <span>寄回物流公司名称</span>
                  <el-popover
                    placement="top"
                    trigger="click"
                    :width="260"
                    :visible="allLogisticsEnterprisePopoverVisible"
                  >
                    <div class="multiple-fill-in-logistics-enterprise">
                      <el-input
                        v-model.trim="allLogisticsEnterprise"
                        placeholder="请输入寄回物流公司"
                      />
                      <h-button type="primary" @click="onConfirmMultipleFillInLogisticsEnterprise">
                        确定
                      </h-button>
                    </div>
                    <template #reference>
                      <h-plain-button
                        :height="16"
                        :padding-lr="4"
                        @click="
                          allLogisticsEnterprisePopoverVisible =
                            !allLogisticsEnterprisePopoverVisible
                        "
                      >
                        批量
                      </h-plain-button>
                    </template>
                  </el-popover>
                </div>
              </template>
              <template #default="{ $index }">
                <el-tooltip
                  :visible="
                    $index === noLogisticsInfoTipSet.tableIndex &&
                    noLogisticsInfoTipSet.noEnterprise
                  "
                  :content="infoTip.returnFactory.detail.no_fill_logistics_enterprise"
                  placement="top"
                >
                  <el-input
                    v-model.trim="form.repairGoodsLogisticsVos[$index].sendBackLogisticsName"
                    placeholder="请输入寄回物流公司"
                  />
                </el-tooltip>
              </template>
            </el-table-column>

            <!-- 寄回物流单号 -->
            <el-table-column label="寄回物流单号" width="160">
              <template #header>
                <div class="table-cell-header">
                  <span>寄回物流单号</span>
                  <el-popover
                    v-model:visible="allLogisticsNoPopoverVisible"
                    placement="top"
                    trigger="click"
                    :width="260"
                  >
                    <div class="multiple-fill-in-logistics-enterprise">
                      <el-input
                        v-model.trim="allLogisticsNo"
                        placeholder="请输入寄回物流单号"
                        clearable
                        @input="handleMultipleFillLogisticsNoInput"
                      />
                      <h-button type="primary" @click="onConfirmMultipleFillInLogisticsNo">
                        确定
                      </h-button>
                    </div>
                    <template #reference>
                      <h-plain-button :height="16" :padding-lr="4">批量</h-plain-button>
                    </template>
                  </el-popover>
                </div>
              </template>
              <template #default="{ $index }">
                <el-tooltip
                  :visible="
                    $index === noLogisticsInfoTipSet.tableIndex && noLogisticsInfoTipSet.noOrderNum
                  "
                  :content="infoTip.returnFactory.detail.no_fill_logistics_no"
                  placement="top"
                >
                  <el-input
                    v-model.trim="form.repairGoodsLogisticsVos[$index].sendBackLogisticsNo"
                    placeholder="请输入寄回物流单号"
                    maxlength="60"
                    clearable
                    @input="(val: string) => handleFillLogisticsNoInput($index, val)"
                  />
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
    <template #footer>
      <h-button is-modal type="primary" @click="onConfirm">确定</h-button>
      <h-button is-modal @click="hideDrawer">取消</h-button>
    </template>
  </h-drawer>
</template>

<style scoped lang="scss">
  .multiple-fill-in-logistics-enterprise {
    display: flex;
    column-gap: 5px;
  }

  .modal_form_content {
    padding: 0 !important;
  }

  .file {
    width: 60px;
    height: 37.5px;

    :deep(.el-upload) {
      width: 100%;
      height: 100%;

      .el-upload-dragger {
        padding: 0;
        width: 100%;
        height: 100%;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
      }
    }
  }

  .drawer-body {
    height: 100%;
    display: flex;
    flex-direction: column;

    .basic-info {
      display: flex;
      flex-direction: column;
      row-gap: 6px;
      margin-bottom: 24px;

      .title {
        font-size: 12px;
        font-weight: bold;
        padding-left: 6px;
        border-left: 3px solid $primaryColor;
      }

      :deep(.el-form) {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        column-gap: 48px;
        row-gap: 12px;
        box-sizing: border-box;

        .el-form-item {
          .el-form-item__label {
            height: 28px;
            line-height: 28px;
          }

          .el-form-item__content {
            align-items: flex-start;

            .el-textarea {
              .el-textarea__inner {
                width: 100% !important;
                min-height: 28px !important;
                height: 28px;
                max-height: 100px !important;
              }
            }

            .el-form-item__error {
              margin: 3px 0 0 0;
              padding: 0;
            }
          }
        }
      }
    }

    .logistics-list {
      display: flex;
      flex-direction: column;
      row-gap: 6px;
      flex: 1;
      height: 0;

      .title {
        font-size: 12px;
        font-weight: bold;
        padding-left: 6px;
        border-left: 3px solid $primaryColor;
      }

      .table {
        max-height: calc(100% - 22px);
      }
    }

    .table-cell-header {
      display: flex;
      align-items: center;
      column-gap: 5px;
    }
  }
</style>
